import Vue from 'vue'
import Vuex from 'vuex'
import Http from './http.js'
import Utils from './utils.js'
import { Indicator } from 'mint-ui'
// import utils from './utils.js';

Vue.use(Vuex)
var maxAge = 120*60*60*1000
const friends = [
  {
    name:'周杰伦',
    head:'https://image.birdpush.com/upload/leaflet/picture/cover/201711/1513233241775.png',
    result:28
  },
  {
    name: '周杰周杰周杰周杰周杰',
    head: 'https://image.birdpush.com/upload/leaflet/picture/cover/201711/1513233241775.png',
    result: 23
  },
  {
    name: '周杰伦',
    head: 'https://image.birdpush.com/upload/leaflet/picture/cover/201711/1513233241775.png',
    result: 9
  },
  {
    name: '杰伦',
    head: 'https://image.birdpush.com/upload/leaflet/picture/cover/201711/1513233241775.png',
    result: 28
  },
  {
    name: '伦',
    head: 'https://image.birdpush.com/upload/leaflet/picture/cover/201711/1513233241775.png',
    result: 28
  },
  {
    name: '伦',
    head: 'https://image.birdpush.com/upload/leaflet/picture/cover/201711/1513233241775.png',
    result: 29
  }
]

var musicMainDom = null

const state = {
  actionTime:new Date('2018-02-09 09:00:00').valueOf(),
  pvId:'64409',  // '58481'  '64409'
  toastText:null,
  showId:null, //分享者id
  isPlaying:true,
  gameAssetsLoading:{
    loaded:0,
    total:0
  },
  animals:0,
  orderTotal:0,
  bestAnimals:0,
  user:null,
  friends: [], //好友排名列表
  coupon:'',
}

const getters = {
  wxShareData: function (state) {
    let data = {
      title: `${state.user?state.user.nickname:''}在杭州银行手机银行最多抓了${state.bestAnimals}只年兽，敢不敢来PK？`,
      desc: "杭州银行的年兽有毒，停不下来",
      link: `${window.location.href.split('#')[0]}#/shareStart?showId=${state.user?state.user.openid:''}`,   
      imgUrl: window.location.href.split('index.html')[0] + 'static/logo.jpg'
    }
    return data
  },
  gameLoadEnd:function (state) {
    return state.gameAssetsLoading.total > 0 && state.gameAssetsLoading.total === state.gameAssetsLoading.loaded
  },
  loadPrecess: function (state) {
    let num = 0
    if (state.gameAssetsLoading.total > 0  ){
      num = state.gameAssetsLoading.loaded / state.gameAssetsLoading.total
    }
    return num
  }
}

const mutations = {
  setWxConfig(state,data){ //微信sdk
    //微信授权页面sdk
    wx.config({
      debug: false, 
      appId: Utils.wxConfig.appid, // 必填，公众号的唯一标识
      timestamp: data.timestamp, // 必填，生成签名的时间戳
      nonceStr: data.nonceStr, // 必填，生成签名的随机串
      signature: data.signature, // 必填，签名，见附录1
      jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
    wx.ready(function () {
      wx.onMenuShareTimeline(getters.wxShareData)
      wx.onMenuShareAppMessage(getters.wxShareData)
    })
  },
  toast(state,str){
    state.toastText = str
  },
  updateMusicStatus(state,status){
    if (!musicMainDom){
      musicMainDom = document.getElementById('music-main')
    }
    if (status ){
      document.getElementById('music-main').play()
    }else{
      document.getElementById('music-main').pause()
    }
    state.isPlaying = status
  },
  updateGameAssetsLoading(state, data){ //游戏资源加载，做进度条展示
    state.gameAssetsLoading.loaded = data.current
    state.gameAssetsLoading.total = data.total
  },
  setShowId(state,id){
    state.showId = id
  },
  setUser(state,data){
    state.user = data
    localStorage.setItem('nianshou_user',JSON.stringify(data)) //  授权用户数据
    localStorage.setItem('nianshou_authorTime',new Date().valueOf()) //授权时间 
  },
  initUser(state){
    console.log('用户信息初始化')
    if (localStorage.getItem('nianshou_authorTime') ){
      // 用过授权
      let t1 = Number(localStorage.getItem('nianshou_authorTime'))
      t1 = new Date().valueOf()-t1
      if (t1 > maxAge){ //缓存有效期 7h
        //过期
        localStorage.clear()
      }
    }
    if ( localStorage.getItem('nianshou_user') ){
      state.user = JSON.parse(localStorage.getItem('nianshou_user'))
      if (localStorage.getItem('nianshou_friends')){
        // state.friends = JSON.parse(localStorage.getItem('nianshou_friends'))
        // state.bestAnimals = Number(localStorage.getItem('nianshou_bestAnimals'))
        // state.orderTotal = Number(localStorage.getItem('nianshou_orderTotal'))
      }
     
    }else{
      // 没登录 或者 缓存过期被清空
      state.user = null
    }
  },
  updateBestAnimals(state,num){
    state.bestAnimals = num
  },
  setFriends(state,data){
    state.friends = data.list.map(ele=>{
      return {
        id:ele.id,
        head:ele.img,
        name:ele.nick,
        openId: ele.openId,
        result: ele.score
      }
    })
    state.bestAnimals = data.score //获取最高分
    state.coupon = data.coupon //新增兑奖码字段
    //state.orderTotal = data.order
    // localStorage.setItem('nianshou_friends', state.friends)
    // localStorage.setItem('nianshou_bestAnimals', state.bestAnimals)
    // localStorage.setItem('nianshou_orderTotal', state.orderTotal) 
  },
  updateAnimals(state, num){ //抓捕结果更新
    state.animals = num
    if (num > state.bestAnimals) { //最高成绩更新
      state.bestAnimals = num
    }
  },
  updateCoupon(state,str){
    state.coupon = str
  },
}

const actions = {
  addGameTime({ commit, state }){ //统计玩游戏次数，测试环境 加上bird_dsp
    let orgUrl = window.location.origin
    const cid = Utils.GetQueries().cid ? Utils.GetQueries().cid : ''
    Http.post(`leaflet/actRecord`, {
      leafletId: state.pvId,
      iswechat: 0,
      leafletName: '杭州银行 抓年兽',
      recordType: 0,
      cid: cid,
      channelName: cid,
      toolType: 0
    })
  },
  addPvUv({ commit, state }){ //添加PV uv统计，测试环境 加上bird_dsp
    let orgUrl = window.location.origin
    let MobDevice = Utils.MobDevice()
    Http.get(`leaflet/addLeafletRecord`, {
      params: {
        leafletId: state.pvId,
        iswechat: 0,
        toolType: 0,
        mobDevice: MobDevice,
        openId: state.user.openid
      }
    })
  },
  getWxConfig({ commit, state }){ // 获取微信授权sdk,测试环境 加上bird_dsp
    let accessUrl = window.location.href.split('#')[0]
    // 微信sdk授权
    return new Promise((resolve, reject) => {
      Http.post(`common/shareInfo?accessUrl=${accessUrl}`).then(res => {
        resolve(res)
      })
    })
  },
  getUserInfo({ commit, state },data){ //获取用户信息
    return new Promise((resolve, reject)=>{
      Http.get('monster/wechat', {
        params: data
      }).then(res=>{
        commit('setUser',res.data.data)
        resolve()
      })
    })
  },
  getFriendsList({ commit, state }, data){
    console.log(state.user)
    return new Promise((resolve, reject) => {
      Http.get('monster/user/among', {
        params: { openId: state.user.openid}
      }).then(res => {
        commit('setFriends', res.data)
        resolve()
      }).catch(()=>{
        reject()
      })
    })
  },
  updateBestAnimals({ commit, state }, data){//更新最佳纪录
    
    return new Promise((resolve, reject) => {
      Http.get('monster/record/score', {
        params: { 
          openId: state.user.openid,
          score: state.animals,
          showId: state.showId 
        }
      }).then(res => {
        //commit('updateBestAnimals', res.data)
        resolve()
      }).catch(()=>{
        reject()
      })
    })
  },
  openAward({ commit, state }){//开奖金  
    return new Promise((resolve, reject) => {
      Indicator.open({
        text: '正在开奖...',
        spinnerType: 'fading-circle'
      })
      Http.get('monster/luckDraw', {
        params: {
          openId: state.user.openid
        }
      }).then(res => {
        Indicator.close()
        if( res.data.count >2 ){
          resolve({
            count:3
          })
          return
        }
        if (res.data.resCode===0){
          //第一次开奖品        
          commit('updateCoupon', res.data.coupon)
          resolve({
            coupon: res.data.coupon,
            count: res.data.count
          })
        } else if (res.data.resCode === 1){
          //已领取 显示未中奖
          reject()
        }else{   
          if(res.data.resCode){
            let str = ''
            switch (res.data.resCode ) {
              case 2:
                str = '活动已结束'
                break;
              case 3:
                str = '您已领取兑奖码'
                break
              default:
                str = '您未中奖'  //兑奖码已领完  
                break
            }
            //commit('toast',str)
            // 显示未中奖
            reject()
          }
        }  
      }).catch(()=>{
        Indicator.close()
        //commit('toast','前方人山人海，请您稍后再试~')
      })
    })
  },
  getShowerInfo({ commit, state },data){ //获取分享人的成绩
    return new Promise((resolve, reject) => {
      Http.get('monster/userInfo', data).then(res => {
        resolve(res.data.user)
      })
    })
  }

}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})